<template>
  <div>
    <el-tabs v-model="tabName" type="border-card">
      <el-tab-pane name="indexList" label="指标列表">
        <div style="display:flex;align-items:center;font-size:15px;"
            element-loading-spinner="el-icon-loading"
            element-loading-text="指标数据更新中"
            v-loading="fileManyUpdateLoading">
            <div v-show="indexList.length>0">
              <el-upload action="''" accept=".xlsx" :before-upload="()=>{return false}"
              :on-change="updateFileChange" :file-list="updateFileList">
                <div class="el-upload__text"><em style="color:#0066FF;">点击选择</em> (文件批量更新指标,仅支持xlsx文件)</div>
              </el-upload>
            </div>
            <div style="margin-left:6px;"><el-input clearable style="width:300px;" size="mini" v-model="queryKeyWord" placeholder="在此输入指标关键字搜索"></el-input></div>
            <div style="margin-left:6px;"><el-button size="mini" type="primary" @click="getIndexesWithKeyWord">搜索</el-button></div>
          <div style="margin-left: auto">
            
          </div>
          <div style="margin-left: auto">
            <span>将我的指标转移给</span>
            <span style="margin-left: 3px">
              <el-select v-model="indexToUserId" filterable size="mini">
                <el-option
                  v-for="u in userList"
                  :key="u.id"
                  :label="u.admin_name"
                  :value="u.id"
                />
              </el-select>
            </span>
            <span style="margin-left: 4px">
              <el-button
                type="primary"
                size="mini"
                :loading="moveLoading"
                @click="toMoveIndexToOther"
              >
                确定转移
              </el-button>
            </span>
            【
            <a :href="modelFileUrl" target="_blank">下载</a>
            】批量上传的文件模板。
          </div>
        </div>
        <div v-if="indexList.length>0">
          <div style="margin-top:5px;">
            <el-table border row-class-name='table-row' :data='indexList'>
              <el-table-column type="expand" label="详细" width='50'>
                <template slot-scope="props">
                  <div style="margin-left:48px;width:550px;">
                    <el-row :gutter="4" type="flex" justify="start" align="middle" style="margin-bottom:10px;font-size:13px;">
                      <el-col :span="2">平台ID</el-col>
                      <el-col :span="4">{{ props.row.source_id }}</el-col>
                    </el-row>
                    <el-row :gutter="4" type="flex" justify="start" align="middle" style="margin-bottom:10px;font-size:13px;">
                      <el-col :span="2">来源</el-col>
                      <el-col :span="4">{{ props.row.raw_source }}</el-col>
                    </el-row>
                    <el-row :gutter="4" type="flex" justify="start" align="middle" style="margin-bottom:10px;font-size:13px;">
                      <el-col :span="2">品种</el-col>
                      <el-col :span="4">{{ props.row.variety }}</el-col>
                    </el-row>
                    <el-row :gutter="4" type="flex" justify="start" align="middle" style="margin-bottom:10px;font-size:13px;">
                      <el-col :span="2">状态</el-col>
                      <el-col :span="4">{{ props.row.state_text }}</el-col>
                    </el-row>
                    <el-row :gutter="4" type="flex" justify="start" align="middle" style="margin-bottom:10px;font-size:13px;">
                      <el-col :span="2">频率</el-col>
                      <el-col :span="4">{{ props.row.frequency }}</el-col>
                      <el-col :span="18"><span style="color:#F06431;">注意：月、季、年频率的数据，维护时日期选择该频率的最后一天！</span></el-col>
                    </el-row>
                    <el-row :gutter="4" type="flex" justify="start" align="middle" style="font-size:13px;">
                      <el-col :span="2"><span style="color:#F06431;font-size:15px;">新增</span></el-col>
                      <el-col :span="7"><el-date-picker v-model="props.row.editDate" size="mini" style="width:160px;"></el-date-picker></el-col>
                      <el-col :span="8"><el-input v-model="props.row.editValue" size="mini" placeholder="输入数据值"></el-input></el-col>
                      <el-col :span="4"><el-button type="success" size="mini" @click="saveEditDateValue(props.row)" :loading="props.row.uploadLoading">保存</el-button></el-col>
                    </el-row>
                    <el-row v-if="!props.row.enddate" :gutter="4" type="flex" justify="start" align="middle" style="font-size:13px;margin-top:10px;">
                      <el-col :span="17">
                        <el-upload action="''" accept=".xlsx,.xls" :before-upload="()=>{return false}"
                         :on-change="(file)=>firstFileChange(file,props.row)" :file-list="[]">
                          <div class="el-upload__text"><em style="color:#0066FF;font-size:15px;">{{ props.row.fileName }}</em> (只能上传xls/xlsx文件)</div>
                        </el-upload>
                      </el-col>
                      <el-col :span="4"><el-button type="primary" size="mini" :disabled="!props.row.firstFile" @click="firstUploadIndex(props.row)" :loading="props.row.uploadLoading">确定上传</el-button></el-col>
                    </el-row>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="ID" prop="id" width="70px"></el-table-column>
              <el-table-column
                label="指标名称"
                prop="name_zh"
                show-overflow-tooltip
              >
                <template slot-scope="scope">
                  <div class="namerow">
                    <span class="namezh">{{ scope.row.name_zh }}</span>
                    <span
                      class="rowactions"
                      @click="toBrushIndexData(scope.row)"
                    >
                      <vab-icon
                        :icon="['fas', 'brush']"
                        class="brush"
                      ></vab-icon>
                    </span>
                    <span class="rowactions" @click="toPopIndexData(scope.row)">
                      <vab-icon :icon="['fas', 'eye']" class="eye"></vab-icon>
                    </span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="频率" prop="frequency" width='50px' show-overflow-tooltip></el-table-column>
              <el-table-column label="源" prop="source_plat" width='50px' show-overflow-tooltip></el-table-column>
              <el-table-column label="源ID" prop="source_id" width="110px" show-overflow-tooltip></el-table-column>
              <el-table-column label="指标单位" prop="unit" width="90px" show-overflow-tooltip></el-table-column>
              <el-table-column label="起始日期" prop="startdate" width="100px"></el-table-column>
              <el-table-column label="结束日期" prop="enddate" width="100px"></el-table-column>
              <el-table-column label="创建时间" prop="create_time" width="140px"></el-table-column>
              <el-table-column label="更新时间" prop="refresh" width="140px"></el-table-column>
            </el-table>
            <el-pagination style="margin-top:5px;"
              background
              :current-page="page"
              :page-size="pageSize"
              layout="total, prev, pager, next, jumper"
              :total="totalCount"
              @current-change="currentPageChanged">
            </el-pagination>
          </div>
        </div>
        <div v-else>
          <el-empty description="您还没有自定义数据指标"></el-empty>
        </div>
      </el-tab-pane>
      <el-tab-pane name="indexCreate" label="新建指标">
        <div style="width:660px;">
          <el-form label-width="80px" ref="indexForm" :model="indexObj" :rules="objRules">
            <el-form-item prop="name_zh" label="指标名称">
              <el-input v-model.trim="indexObj.name_zh" type="text" placeholder="输入数据的指标名称"></el-input>
            </el-form-item>
            <el-form-item  prop="frequency" label="频率">
              <el-select v-model="indexObj.frequency" placeholder="选择数据更新频率">
                <el-option v-for="item,index in frequencyList" :label="item.label" :value="item.value" :key="item.value"></el-option>
              </el-select>
              <span style="color:#F06431;font-size:11px;">上传时，月、季、年频率的日期请使用该频率的最后一天。</span>
            </el-form-item>
            <el-form-item label="指标单位">
              <el-input v-model.trim="indexObj.unit" placeholder="输入数据指标单位"></el-input>
            </el-form-item>
            <el-form-item label="数据来源">
              <el-input v-model.trim="indexObj.raw_source" placeholder="输入数据指标原始来源"></el-input>
            </el-form-item>
            <el-form-item prop="start_date" label="起始时间">
              <el-date-picker v-model="indexObj.start_date" placeholder="输入数据开始的日期"></el-date-picker>
            </el-form-item>
            <el-form-item label="品种">
              <el-select v-model="selectedVarieties" multiple filterable>
                <el-option v-for="v,i in varietyList" :value="v.variety_en" :label="v.variety_long_name" :key="i"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="备注">
              <el-input v-model.trim="indexObj.note" placeholder="数据备注"></el-input>
            </el-form-item>
            <el-form-item label="更新状态">
              <el-radio v-model="indexObj.state" :label="1">正常</el-radio>
              <el-radio v-model="indexObj.state" :label="0">停止更新</el-radio>
            </el-form-item>
          </el-form>
          <div style="float: right;">
            <el-button type="infor" @click="resetIndexObj">重置</el-button>
            <el-button type="primary" @click="toSaveIndex" :loading="saveIndexLoading">确定保存</el-button>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 指标数据详情弹窗 -->
    <IndexDetaiPopup
      :indexId="currentDetailId"
      :show="showIndexDetail"
      :title="detailDialogTitle"
    ></IndexDetaiPopup>
  </div>
</template>

<script>
  let NAME_SPACE = 'V03'
  import IndexDetaiPopup from '@/components/DataIndex'
  import { fileStorage } from '@/config'
  import { getAnalystList } from '@/api/user'
  import { getUserAuthVariety } from '@/api/operations/variety'
  import {
    addCustomEDBTable,
    getCustomEDBTable,
    updateIndexWithFile,
    insertIndexValue,
    updateManyIndexesWithFile,
    getFileUpdateState,
    brushEDBTable,
    moveCustomerIndex,
  } from '@/api/edbdata/datalib'
  import { datetimeToStr } from '@/utils/datetimeUtils'
  export default {
    components: {
      IndexDetaiPopup,
    },
  data(){
    return {
      modelFileUrl: fileStorage + 'AppFiles/templates/数据库指标更新.xlsx',
      tabName: 'indexList',
      indexList: [],
      page: 1,
      pageSize: 50,
      totalCount: 0,
      queryKeyWord: '',

      frequencyList: [{label: '年', value: '年'},  {label: '季', value: '季'}, {label: '月', value: '月'}, {label: '周', value: '周'}, {label: '日', value: '日'}],
      varietyList: [],
      selectedVarieties: [],
      indexObj: {
        source_plat: 'rj',
        name_zh: '',
        frequency: null,
        unit: '',
        raw_source: '',
        startdate: null,
        note: '',
        state: 1,
        is_open: 1,
        variety: ''
      },
      objRules: {
        name_zh: [{ required: true, message: '请输入指标名称', trigger: 'blur' }],
        frequency: [{ required: true, message: '请选择指标频率', trigger: 'change' }],
        start_date: [{type: 'date', required: true, message: '请选择数据开始日期', trigger: 'change'}]
      },
      saveIndexLoading: false,

      newDataDate: new Date(),

      updateFileList: [], // 选择更新的文件
      fileManyUpdateLoading: false,
      fileManyUpdateStateTimer: null,

      // 弹窗显示数据
      // 数据详情组件
      detailDialogTitle: '数据详情',
      currentDetailId: -1,
      showIndexDetail: false,
      userList: [],
        indexToUserId: null,
        moveLoading: false,
      }
  },
  mounted() {
    getUserAuthVariety({space: NAME_SPACE}).then(res => {
      this.varietyList = res.data
    })
    this.queryMyIndexes()
    this.getResearchList()
  },
  beforeDestroy() {
    clearInterval(this.fileManyUpdateStateTimer)
    this.fileManyUpdateStateTimer = null
  },
  methods:{
    resetIndexObj(){
      this.indexObj.source_plat='rj'
      this.indexObj.name_zh = ''
      this.indexObj.frequency = null
      this.indexObj.unit = ''
      this.indexObj.raw_source = ''
      this.indexObj.start_date = null
      this.indexObj.note = ''
      this.indexObj.state = 1
      this.indexObj.is_open = 1
    },

      // 获取分析师列表
      getResearchList() {
        getAnalystList().then((res) => {
          this.userList = res.data
        })
      },
      // 转移自定义指标给别人
      toMoveIndexToOther() {
        if (!this.indexToUserId) return
        this.moveLoading = true
        moveCustomerIndex(this.indexToUserId)
          .then((res) => {
            this.$baseMessage(res.msg, 'success')
            this.moveLoading = false
            this.queryMyIndexes()
          })
          .catch(() => {
            this.moveLoading = false
          })
      },

    // 关键字查询自定义指标
    getIndexesWithKeyWord(){
      const keyword = this.queryKeyWord.trim()
      this.queryMyIndexes(keyword)
    },

    // 文件批量更新的文件变化
    updateFileChange(file, fileList){
      // 将文件上传更新
      const formData = new FormData()
      formData.append("file", file.raw)
      this.fileManyUpdateLoading = true
      updateManyIndexesWithFile(formData).then(res => {
        // this.$baseMessage(res.msg, 'success')
        console.log('更新完成！');
        clearInterval(this.fileManyUpdateStateTimer)
        this.fileManyUpdateStateTimer = null
        this.fileManyUpdateStateTimer = setInterval(this.queryFileManyUpdateState,1000)
      }).catch(err => {
        // this.$baseMessage('批量更新出错!', 'error')
        // this.fileManyUpdateLoading = false
        // 由于采用了状态调用，此处不管成功失败，启用状态查询
        clearInterval(this.fileManyUpdateStateTimer)
        this.fileManyUpdateStateTimer = null
        this.fileManyUpdateStateTimer = setInterval(this.queryFileManyUpdateState,1000)
      })
    },

    // 查询文件批量更新状态
    queryFileManyUpdateState(){
      getFileUpdateState().then(res => {
        console.log(res);
        if (parseInt(res.data.state) === 0){
          this.fileManyUpdateLoading = false
          this.$baseMessage('数据更新完毕！', 'success')
          clearInterval(this.fileManyUpdateStateTimer)
          this.fileManyUpdateStateTimer = null
          this.queryMyIndexes()  // 刷新数据
        }
      }).catch(err => {
        clearInterval(this.fileManyUpdateStateTimer)
        this.fileManyUpdateStateTimer = null
      })
    },


    // 点击保存数据指标
    toSaveIndex(){
      this.$refs.indexForm.validate((valid) => {
        if (!valid){
          return
        }
        this.indexObj.startdate = datetimeToStr(this.indexObj.start_date, true, '-')
        this.indexObj.variety = this.selectedVarieties.join(',')
        this.saveIndexLoading = true
        addCustomEDBTable(this.indexObj).then(res => {
          this.$baseMessage(res.msg, 'success')
          this.resetIndexObj()
          this.queryMyIndexes()
          this.tabName = 'indexList'
          this.saveIndexLoading = false
        }).catch(err=> {
          console.log(err);
          this.saveIndexLoading = false
        })
      })
    },

    // 查询指标列表
    queryMyIndexes(keyword){
      const params = {
        page: this.page,
        page_size: this.pageSize,
        kw: keyword?keyword:null
      }
      getCustomEDBTable(params).then(res => {
        const data = res.data
        this.indexList = data.data.map(item=>{
          item.editValue=null;
          item.firstFile = null
          item.fileName = '用文件首次上传数据'
          item.uploadLoading = false
          let curYear = new Date().getFullYear()
          let curMonth = new Date().getMonth() + 1
          if (item.frequency === '月'){
            item.editDate=new Date(curYear, curMonth, 0)
          }else if (item.frequency === '季'){
            if (curMonth <= 3){item.editDate=new Date(curYear, 3, 0)}
            else if (curMonth <= 6){item.editDate=new Date(curYear, 6, 0)}
            else if (curMonth <= 9){item.editDate=new Date(curYear, 9, 0)}
            else{item.editDate=new Date(curYear, 12, 0)}
          }else if (item.frequency === '年'){
            item.editDate=new Date(curYear, 12, 0)
          }else{
            item.editDate = new Date()
          }
          return item
        })
        this.page = data.page
        this.totalCount = data.total_count
      })
    },

      // 保存该日期的数据
      saveEditDateValue(row) {
        const data = {
          dataid: row.id,
          row_value: [{datadate: datetimeToStr(row.editDate, true, '-'), datavalue: row.editValue}]
        }
        row.uploadLoading = true
        insertIndexValue(data)
          .then((res) => {
            console.log(res)
            if (res.code === 200) {
              this.$baseMessage(res.msg, 'success')
              row.enddate = res.data.enddate
              row.refresh = res.data.refresh
              row.editValue = null
              row.uploadLoading = false
            } else {
              this.$baseMessage(res.msg, 'error')
              row.uploadLoading = false
            }
          })
          .catch(() => {
            row.uploadLoading = false
          })
      },

      // 首次上传数据的文件变化
      firstFileChange(file, row) {
        row.fileName = file.name
        row.firstFile = file.raw
      },

      // 确定首次上传数据
      firstUploadIndex(row) {
        console.log(row);
        const formData = new FormData()
        formData.append("file", row.firstFile)
        formData.append("iid", row.id)
        row.uploadLoading = true
        updateIndexWithFile(formData).then(res => {
          console.log(res);
          if (res.code === 201){
            this.$baseMessage(res.msg, 'success')
            row.enddate = res.data.enddate
            row.refresh = res.data.refresh
            row.uploadLoading = false
          }else{
            this.$baseMessage(res.msg, 'error')
            row.uploadLoading = false
          }
        }).catch(()=> {
          row.uploadLoading = false
        })
      },

      // 点击查看编辑数据
      toPopIndexData(row) {
        this.currentDetailId = row.id
        this.detailDialogTitle = row.name_zh
        this.showIndexDetail = true
      },

      // 点击清除数据
      toBrushIndexData(row) {
        const tipMsg = `清空【${row.name_zh}】\n并重新设置一个起始日期?\n(yyyy-mm-dd)`
        this.$prompt(tipMsg, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        })
          .then(({ value }) => {
            const startDate = value ? value.trim() : ''
            const brushData = {
              index_id: row.id,
              start_date: startDate ? startDate : '',
            }
            brushEDBTable(brushData).then((res) => {
              if (res.code === 200) {
                this.$baseMessage(res.msg, 'success')
                this.queryMyIndexes()
              } else {
                this.$baseMessage(res.msg, 'error')
              }
            })
          })
          .catch(() => {})
      },

      // 指标列表页码变化
      currentPageChanged(page) {
        this.page = page
        this.queryMyIndexes()
      },
    },
  }
</script>

<style scoped lang="scss">
  .showactions {
    opacity: 1;
  }
  .namerow {
    .rowactions {
      float: right;
      opacity: 0;
      cursor: pointer;
      color: #1e51db;
      .brush {
        color: #c04546;
        transform: rotate(-135deg);
        margin-left: 10px;
      }
    }
    &:hover {
      .rowactions {
        @extend .showactions;
      }
    }
  }
</style>
